package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.dto.ArticleDto;
import com.heima.article.entity.ApArticle;
import com.heima.common.aliyun.service.AliyunGreenService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.MediaEnum;
import com.heima.common.minio.service.MinIOService;
import com.heima.common.util.SensitiveWordUtil;
import com.heima.feign.article.ArticleFeign;
import com.heima.media.dto.ContentDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmSensitive;
import com.heima.media.entity.WmUser;
import com.heima.media.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-07-03 11:06
 */
@Service
public class AuditServiceImpl implements IAuditService {

    @Autowired
    private IWmUserService wmUserService;

    @Autowired
    private IWmChannelService channelService;


    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IWmNewsService wmNewsService;

    @Autowired
    private AliyunGreenService aliyunGreenService;

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IWmSensitiveService sensitiveService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 审核自媒体文章（自媒体用户发布，爬取，人工审核）
     *
     * @param wmNews
     */
    @Override
    @Async
    public void audit(WmNews wmNews) {
        //获取自媒体目前文章审核状态
        Integer status = wmNews.getStatus();

        //1.如果是自动审核通过待发布|人工审核通过
        if (status.equals(MediaEnum.NEWS_SUBMIT_STATUS_ARTIFICIAL_PASS.getVal()) || status.equals(MediaEnum.NEWS_SUBMIT_STATUS_PASS.getVal())) {
            //1.1 判断系统时间是否大于自媒体文章发布时间
            if (System.currentTimeMillis() >= wmNews.getPublishTime().getTime()) {
                //1.2 大于：则远程调用文章微服务发布文章
                remotePublishArticle(wmNews);
                return;
            }
        }

        //2.如果是待审核，进入自动审核业务流程中
        //2.1 从自媒体文章正文中获取文本跟图片
        Map<String, Object> textAndImageMap = getTextAndImageFromContent(wmNews.getContent());

        //2.0 检测敏感词
        boolean flag = checkSensitive(textAndImageMap.get("text").toString(), wmNews);
        if (!flag) {
            return;
        }
        //2.2 调用阿里云内容安全审核文本(文章标题+文章正文)
        String allText = wmNews.getTitle() + textAndImageMap.get("text");


        flag = checkText(allText, wmNews);
        if (!flag) {
            //包含违规内容
            return;
        }

        //2.3 调用阿里云内容安全审核图片（文章封面+文章正文包含图片）
        List<String> allImageList = new ArrayList<>();
        List<String> contentIamges = (List<String>) textAndImageMap.get("images");
        if (!CollectionUtils.isEmpty(contentIamges)) {
            allImageList.addAll(contentIamges);
        }
        String images = wmNews.getImages();
        if (StringUtils.isNotBlank(images)) {
            //采用逗号分隔
            String[] split = images.split(",");
            List<String> strings = Arrays.asList(split);
            allImageList.addAll(strings);
        }
        flag = checkImage(allImageList, wmNews);
        if (!flag) {
            //包含违规图片
            return;
        }

        //2.4 判断是否到发布时间  （两种情况：1.未到发布时间：修改状态为自动审核通过待发布；2.已经到发布时间，远程发布接口）
        if (System.currentTimeMillis() >= wmNews.getPublishTime().getTime()) {
            //2.4.1 已经到了发布时间，进行正式发布
            remotePublishArticle(wmNews);
        } else {
            //2.4.2 审核通过，但是没有到发布时间，修改状态；
            wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_PASS.getVal());
            wmNewsService.updateById(wmNews);
            //TODO 基于Redison延迟任务实现延迟发布
            //计算延迟发布时间 未来发布时间-当前系统数据
            long delayTime = wmNews.getPublishTime().getTime() - System.currentTimeMillis();
            //1.创建阻塞队列
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("test-dqueue");
            //2.创建延迟队列
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //3.发送延迟消息
            delayedQueue.offer(wmNews.getId() + "", delayTime, TimeUnit.MILLISECONDS);
        }
    }


    /**
     * 基于自媒体文章对象构建正式发布文章对象ApArticle;远程调用文章微服务发布文章；更新自媒体文章表中逻辑外键：article_id
     *
     * @param wmNews 自媒体文章对象
     */
    private void remotePublishArticle(WmNews wmNews) {
        //1.构建正式发布文章对象：ApArticle
        ArticleDto article = new ArticleDto();
        //1.1 从自媒体文章对象拷贝：封装文章基本信息
        BeanUtils.copyProperties(wmNews, article);

        //1.2 设置作者信息
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        if (wmUser != null) {
            article.setAuthorName(wmUser.getName());
            article.setAuthorId(wmUser.getApAuthorId());
        }
        //1.3 设置频道信息
        WmChannel wmChannel = channelService.getById(wmNews.getChannelId());
        if (wmChannel != null) {
            article.setChannelId(wmChannel.getId());
            article.setChannelName(wmChannel.getName());
        }

        //1.4 设置文章布局
        article.setLayout(wmNews.getType());

        //1.5 设置文章标记
        article.setFlag(MediaEnum.ARTICLE_FLAG_NORMAL.getVal());

        //1.6 TODO 设置省市区 从用户中获取
        article.setProvinceId(1);
        article.setCityId(1);
        article.setCountyId(102);


        //2.远程调用文章微服务 发布正式文章
        ResponseResult<Long> result = articleFeign.saveArticle(article);
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            Long articleId = result.getData();
            //3.更新自媒体文章表中逻辑外键：article_id
            wmNews.setArticleId(articleId);
            wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_PUBLISH.getVal());
            wmNews.setEnable(true);
            wmNewsService.updateById(wmNews);
        }
    }

    /**
     * 直接拷贝 从正文中获取图片 文本
     *
     * @param content
     * @return
     */
    private Map<String, Object> getTextAndImageFromContent(String content) {
        //0.定义文本结果
        StringBuilder stringBuilder = new StringBuilder();
        //0.1 定义图片集合
        List<String> images = new ArrayList<>();
        Map<String, Object> mapResult = new HashMap<>();
        //1.将内容转为JSON数组
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        //2.遍历数组对象 获取文本以及图片
        for (ContentDto dto : contentDtos) {
            if ("text".equals(dto.getType())) {
                stringBuilder.append(dto.getValue());
            } else {
                images.add(dto.getValue());
            }
        }
        mapResult.put("text", stringBuilder.toString());
        mapResult.put("images", images);
        return mapResult;
    }


    /**
     * 直接拷贝:阿里云图片审核:审核自媒体文章对象中：封面，正文中图片,更新自媒体文章状态
     *
     * @param images 封面+正文中图片
     * @param wmNews 自媒体文章对象
     * @return
     */
    private boolean checkImage(List<String> images, WmNews wmNews) {
        boolean result = false;
        // 如果没有图片,不需要进行图片审核,直接返回true
        if (images.size() <= 0) {
            return true;
        }
        try {
            // 调用阿里云图片审核
            // Map map = imageScan.checkUrl(images);    // 如果minio部署在外网服务器,可以直接通过URL地址来审核
            // 先将图片从minio服务器下载下来,然后调用阿里云进行审核
            List<byte[]> imageList = new ArrayList<>();
            for (String url : images) {
                // 下载图片 TODO:下载图片来源地址 图片都是从MinIO来的
                InputStream inputStream = minIOService.download(url);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                imageList.add(bytes);
            }
            Map map = aliyunGreenService.imageScan(imageList);
            String suggestion = (String) map.get("suggestion");
            // 判断结果
            switch (suggestion) {
                case "pass":
                    // 审核通过
                    result = true;
                    break;
                case "block":
                    // 审核不通过
                    wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_FAIL.getVal());
                    // 获取不通过的原因
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云图片审核不通过: " + label);
                    wmNewsService.updateById(wmNews);
                    break;
                case "review":
                    // 人工审核
                    wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_ARTIFICIAL.getVal());
                    wmNewsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("审核图片失败");
        }
        return result;
    }

    /**
     * 阿里云文本审核，更新自媒体文章状态
     *
     * @param text   文章文本
     * @param wmNews 自媒体文章对象
     * @return
     */
    private boolean checkText(String text, WmNews wmNews) {
        boolean result = false;
        try {
            Map map = aliyunGreenService.greenTextScan(text);
            String suggestion = (String) map.get("suggestion");
            // 判断结果
            switch (suggestion) {
                case "pass":
                    // 审核通过
                    result = true;
                    break;
                case "block":
                    // 审核不通过
                    wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_FAIL.getVal());
                    // 获取不通过的原因
                    String label = (String) map.get("label");
                    wmNews.setReason("阿里云文本审核不通过: " + label);
                    wmNewsService.updateById(wmNews);
                    break;
                case "review":
                    // 人工审核
                    wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_ARTIFICIAL.getVal());
                    wmNewsService.updateById(wmNews);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("审核内容失败");
        }
        return result;
    }


    /**
     * 检查传入的文本是否包含敏感词
     *
     * @param text   文本
     * @param wmNews 自媒体用户发布的文章
     * @return
     */
    private boolean checkSensitive(String text, WmNews wmNews) {
        boolean result = false;
        //1.判断敏感词工具中的map是否为空，如果为空，从数据库中加载敏感词到Map中
        if (CollectionUtils.isEmpty(SensitiveWordUtil.dictionaryMap)) {
            LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(WmSensitive::getSensitives);
            //1.1 查询敏感词表中名称列
            List<WmSensitive> sensitiveList = sensitiveService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(sensitiveList)) {
                List<String> collect = sensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
                //1.2 初始化敏感词map
                SensitiveWordUtil.initMap(collect);
            }
        }
        //2. 审核标题
        Map<String, Integer> mapTitle = SensitiveWordUtil.matchWords(wmNews.getTitle());
        if (mapTitle.size() <= 0) {
            //2.1 文章标题审核通过
            //2.1.1 继续审核文章内容是否包含敏感词
            Map<String, Integer> mapContent = SensitiveWordUtil.matchWords(text);
            if (CollectionUtils.isEmpty(mapContent)) {
                //内容审核不包含敏感词
                result = true;
            } else {
                //2.1.3 内容审核失败
                wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_FAIL.getVal());
                Set<String> keySet = mapContent.keySet();
                String join = String.join(",", keySet);
                wmNews.setReason("内容中包含敏感词：" + join);
                wmNewsService.updateById(wmNews);
            }
        } else {
            //2.2 文章标题审核失败
            wmNews.setStatus(MediaEnum.NEWS_SUBMIT_STATUS_FAIL.getVal());
            Set<String> keySet = mapTitle.keySet();
            String join = String.join(",", keySet);
            wmNews.setReason("标题中包含敏感词：" + join);
            wmNewsService.updateById(wmNews);
            return false;
        }
        return result;
    }
}
